package com.learn.educourseboot.service.impl;

import com.learn.eduapi.entity.course.Course;
import com.learn.educourseboot.mapper.CourseDao;
import com.learn.educourseboot.service.CourseService;
import com.learn.educourseboot.util.RedisUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public List<Course> getCrouseList() {
        return courseDao.getCrouseList();
    }

    @Override
    public List<Course> selectByIds(@Param("courseId") String courseId) {
        return courseDao.getAllCourseById(courseId);
    }

    @Override
    public Integer getAllCourseSize(@Param("nowPage")Integer nowPage, @Param("pageSize")Integer pageSize) {
        System.out.println("====先查询Redis====");
        String Page = nowPage.toString();
        Integer totalNum = (Integer)redisUtils.get(Page+"Size");
        if (totalNum==null){
//            同步代码块(双层检测锁)
            synchronized (this) {
                totalNum = (Integer)redisUtils.get(Page+"Size");
                if (totalNum==null) {
                    //去数据库
                    System.out.println("====MySql数据库====");
                    totalNum = courseDao.getAllCourse(nowPage,pageSize).size();
                    // 把从数据库查询的集合放在redis内存中
                    redisUtils.set(Page+"Size", totalNum, 10, TimeUnit.SECONDS);
                }
            }
        }
        return totalNum;
    }

    @Override
    public List<Course> getAllCourse(@Param("nowPage")Integer nowPage, @Param("pageSize")Integer pageSize) {
        System.out.println("====先查询Redis====");
        String Page = nowPage.toString();
        List<Course> list = (List<Course>)redisUtils.get(Page+"allCourses");
        if (list==null){
//            同步代码块(双层检测锁)
            synchronized (this) {
                list = (List<Course>) redisUtils.get(Page+"allCourses");
                if (list==null) {
                    //去数据库
                    System.out.println("====MySql数据库====");
                    list = courseDao.getAllCourse(nowPage,pageSize);
                    // 把从数据库查询的集合放在redis内存中
                    redisUtils.set(Page+"allCourses", list, 10, TimeUnit.SECONDS);
                }
            }
        }

        return list;
    }
}
